package com.xp.record25.bio.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Objects;

public class NettyClient {

    public static void main(String[] args) {
        NioEventLoopGroup group = null;
        try {
            group = new NioEventLoopGroup();
            ChannelFuture channelFuture = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //发送方还必须使用和接受方的配对才行，不然都收不到消息
                            ch.pipeline().addLast(new StringEncoder());
//                            ch.pipeline().addLast(new StringDecoder());
                        }
                    })
                    .connect(new InetSocketAddress(8888));
            System.out.println("-----------连接中------------");
            channelFuture.sync();
            System.out.println("-----------连接成功------------");
            Channel channel = channelFuture.channel();
            channel.writeAndFlush("Hello World");
            System.out.println("-----------发送消息成功------------");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(group)) {
                group.shutdownGracefully();
            }
        }
    }

}
